package jmine.tec.web.wicket.component.menu.cfg;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * Fábrica de MenuConfig que tem como base um xml de configuração.
 * 
 * @author lundberg
 */
public class MenuConfigXMLFactoryBean extends AbstractMenuConfigFactoryBean {

    private URL menuSource;

    /**
     * Construtor
     * 
     * @param menuSource menuSource
     */
    public MenuConfigXMLFactoryBean(URL menuSource) {
        super();
        this.menuSource = menuSource;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected MenuConfig createMenuConfig() {
	XStream xstream = new XStream(null, new DomDriver("UTF-8"), Thread.currentThread().getContextClassLoader());
        xstream.processAnnotations(MenuConfig.class);
        xstream.processAnnotations(MenuConfigItem.class);
        InputStream input = null;
        try {
            input = this.menuSource.openStream();
            return (MenuConfig) xstream.fromXML(input);
        } catch (IOException e) {
            throw new IllegalArgumentException("Não foi possível ler o arquivo de menu fornecido: " + this.menuSource, e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    }
}
